package com.xiaoshuidi.cloud.module.report.service.ajreport;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.oss.core.OosFileService;
import com.xiaoshuidi.cloud.framework.security.core.LoginUser;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.report.constant.CustomTypeEnum;
import com.xiaoshuidi.cloud.module.report.controller.ajreport.vo.*;
import com.xiaoshuidi.cloud.module.report.controller.finance.vo.ExportRespVO;
import com.xiaoshuidi.cloud.module.report.convert.ajreport.ReportRoomReverseConvert;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.ReportRentPeriodDetailsDO;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.ReportRoomReserveDO;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.ReportRoomReserveMapper;
import com.xiaoshuidi.cloud.module.report.enums.ErrorCodeConstants;
import com.xiaoshuidi.cloud.module.report.framework.security.config.ConfigValues;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class ReportRoomReserveServiceImpl implements ReportRoomReserveService {

    private final ReportRoomReserveMapper reportRoomReserveMapper;
    private final ConfigValues configValues;
    private final OosFileService oosFileService;

    /**
     * 预定台账列表查询
     */
    public PageResult<ReportRoomReserveRespVO> roomReversePage(ReportRoomReverseReqVO reqVO){
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        Page<ReportRoomReserveDO> page = new Page<>(reqVO.getPageNo(), reqVO.getPageSize());
        LambdaQueryWrapper<ReportRoomReserveDO> queryWrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(reqVO.getApartmentId())) {
            queryWrapper.eq(ReportRoomReserveDO::getApartmentId, reqVO.getApartmentId());
        }
        if (StringUtils.isNotBlank(reqVO.getCustomerType())) {
            queryWrapper.eq(ReportRoomReserveDO::getCustomerType, reqVO.getCustomerType());
        }
        if (StringUtils.isNotBlank(reqVO.getArea())) {
            queryWrapper.like(ReportRoomReserveDO::getArea, reqVO.getArea());
        }
        //状态搜索
        queryWrapper.eq(StrUtil.isNotBlank(reqVO.getStatus()),ReportRoomReserveDO::getStatus,reqVO.getStatus());
        if (!ObjectUtils.isEmpty(reqVO.getCheckInDateEnd()) && !ObjectUtils.isEmpty(reqVO.getCheckInDateStart())) {
            queryWrapper.ge(ReportRoomReserveDO::getCheckInDate, reqVO.getCheckInDateStart());
            queryWrapper.le(ReportRoomReserveDO::getCheckInDate, reqVO.getCheckInDateEnd());
        }
        if (StringUtils.isNotBlank(reqVO.getMixQueryParam())) {
            queryWrapper.and(wrapper->  wrapper.like(ReportRoomReserveDO::getBooker, reqVO.getMixQueryParam()).or()
                    .like(ReportRoomReserveDO::getBookerPhone, reqVO.getMixQueryParam()).or()
                    .like(ReportRoomReserveDO::getHouseResource, reqVO.getMixQueryParam()));
        }
        queryWrapper.eq(ReportRoomReserveDO::getTenantId,loginUser.getTenantId());
        queryWrapper.eq(ReportRoomReserveDO::getHandleFlag,1);
//        queryWrapper.orderByDesc(ReportRoomReserveDO::getUpdateTime);
        queryWrapper.last("ORDER BY SUBSTRING_INDEX(house_resource,'栋',-1) ASC");
        page = reportRoomReserveMapper.selectPage(page, queryWrapper);
        if(page.getTotal()==0){
            return new PageResult<>(0L);
        }
        PageResult<ReportRoomReserveDO> pageResult = new PageResult<>(page.getRecords(), page.getTotal());

        return  ReportRoomReverseConvert.INSTANCE.convertPage(pageResult);
    }


    /**
     * 预定台账表导出
     */
    public ExportRespVO roomReverseExprot(ReportRoomReverseReqVO req){
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        req.setTenantId(loginUser.getTenantId());
        long count = reportRoomReserveMapper.countReverseForExport(req);
        if (count <= 0) {
            throw new ServiceException(ErrorCodeConstants.ROOM_REVERSE_NOT_EXISTS);
        }
        int pageSize = 2000;
        int totalPage = (int) count / pageSize;
        if (count % pageSize != 0) {
            totalPage++;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String format = sdf.format(new Date());
        String fileName = format + "预定台账.xlsx";

        String filePath = configValues.getNfsPath() + File.separator + fileName;
        ExcelWriter excelWriter = EasyExcel.write(filePath, ReportRoomReserveExportVO.class).build();
        WriteSheet sheet = EasyExcel.writerSheet("sheet1").build();
        for (int i = 1; i <= totalPage; i++) {
            List<ReportRoomReserveDO> infoDOList = reportRoomReserveMapper.selectReverseListForExport(req, (i - 1) * pageSize, pageSize);
            List<ReportRoomReserveExportVO> list = ReportRoomReverseConvert.INSTANCE.convertList(infoDOList);
            excelWriter.write(list, sheet);
        }
        excelWriter.finish();
        //上传到oos返回URL
        String url = oosFileService.oosUploadFile(new File(filePath));
        ExportRespVO resp = new ExportRespVO();
        if(url.startsWith("http:")){
            url = url.replace("http:","https:");
        }
        resp.setUrl(url);
        resp.setFileName(fileName);
        return resp;
    }

}
